<template>
  <div
      class="homepage-container"
      :style="{ backgroundImage: `url(${currentBackground})` }"
      @contextmenu.prevent="handleGlobalContextMenu"
      @wheel="handleGlobalWheel"
  >
    <!-- 右键菜单 -->
    <div
        v-if="contextMenuVisible"
        :style="{ left: contextMenuX + 'px', top: contextMenuY + 'px' }"
        class="context-menu"
    >
      <div v-if="isCategoryContextMenu" class="menu-item" @click="showCategoryIconSettings">
        编辑分类
      </div>
      <div v-if="isCategoryContextMenu" class="menu-item danger" @click="deleteCategory">
        删除分类
      </div>
      <div v-if="isIconContextMenu" class="menu-item" @click="showLayoutSettings">
        布局设置
      </div>
      <div v-if="isIconContextMenu" class="menu-item" @click="showEditSite">
        编辑网站
      </div>
      <div v-if="isIconContextMenu" class="menu-item danger" @click="deleteSite(contextMenuTargetIndex)">
        删除网站
      </div>
      <div  v-if="!isCategoryContextMenu&&!isIconContextMenu" class="menu-item" @click="addNewSite">添加新网站</div>
      <div  v-if="!isCategoryContextMenu&&!isIconContextMenu" class="menu-item" @click="showWallpaperSettings">壁纸设置</div>
      <div  v-if="!isCategoryContextMenu&&!isIconContextMenu" class="menu-item" @click="resetLayout">重置布局</div>
      <div  v-if="!isCategoryContextMenu&&!isIconContextMenu" class="menu-item" @click="importBookmarks">导入书签</div>
    </div>

    <!-- 布局设置面板 -->
    <div v-if="layoutSettingsVisible" class="layout-settings-overlay" @click.self="layoutSettingsVisible = false">
      <div class="layout-settings-panel">
        <h3>布局设置</h3>
        <div class="layout-options">
          <div
              v-for="(option, index) in layoutOptions"
              :key="index"
              class="layout-option"
              :class="{ active: selectedLayout === option.value }"
              @click="setLayout(option.value)"
          >
            <div class="layout-preview" :style="getPreviewStyle(option)">
              <div class="layout-icon"></div>
            </div>
            <div class="layout-label">{{ option.label }}</div>
          </div>
        </div>
        <div class="button-group">
          <button @click="layoutSettingsVisible = false">取消</button>
          <button @click="applyLayout">应用</button>
        </div>
      </div>
    </div>

    <!-- 壁纸设置面板 -->
    <div v-if="wallpaperSettingsVisible" class="wallpaper-settings-overlay" @click.self="wallpaperSettingsVisible = false">
      <div class="wallpaper-settings-panel">
        <h3>壁纸设置</h3>

        <div class="wallpaper-options">
          <div
              v-for="(wallpaper, index) in presetWallpapers"
              :key="index"
              class="wallpaper-option"
              :class="{ active: currentBackground === wallpaper.url }"
              @click="selectWallpaper(wallpaper.url)"
          >
            <div class="wallpaper-preview" :style="{ backgroundImage: `url(${wallpaper.url})` }"></div>
            <div class="wallpaper-label">{{ wallpaper.name }}</div>
          </div>
        </div>
        <div class="custom-wallpaper">
          <h4>自定义壁纸</h4>
          <div class="form-group">
            <input
                type="text"
                v-model="customWallpaperUrl"
                placeholder="输入壁纸URL"
                class="custom-wallpaper-input"
            />
            <button @click="setCustomWallpaper" class="custom-wallpaper-btn">应用</button>
          </div>
        </div>
        <div class="button-group">
          <button @click="wallpaperSettingsVisible = false">取消</button>
          <button @click="saveWallpaperSettings">保存</button>
        </div>
      </div>
    </div>

    <!-- 模态框：添加新网站 -->
    <div v-if="modalVisible" class="modal-overlay" @click.self="modalVisible = false">
      <div class="modal-content">
        <h3>添加新网站</h3>
        <div class="form-group">
          <label>网站名称</label>
          <input v-model="newSiteName" type="text" />
        </div>
        <div class="form-group">
          <label>网站描述</label>
          <input v-model="newSiteDesc" type="text" />
        </div>
        <div class="form-group">
          <label>网站URL</label>
          <input v-model="newSiteUrl" type="text" />
        </div>
        <div class="form-group">
          <label>网站图标URL</label>
          <input v-model="newSiteIcon" type="text" />
        </div>
        <div class="button-group" style="justify-content: center; gap: 10px; margin-top: 20px;">
          <button @click="modalVisible = false">取消</button>
          <button @click="saveNewSite">保存</button>
        </div>
      </div>
    </div>


    <!-- 模态框：编辑新网站 -->
    <div v-if="editModalVisible" class="modal-overlay" @click.self="editModalVisible = false">
      <div class="modal-content">
        <h3>编辑网站</h3>
        <div class="form-group">
          <label>网站名称</label>
          <input v-model="siteName" type="text" />
        </div>
        <div class="form-group">
          <label>网站描述</label>
          <input v-model="siteDesc" type="text" />
        </div>
        <div class="form-group">
          <label>网站URL</label>
          <input v-model="siteUrl" type="text" />
        </div>
        <div class="form-group">
          <label>网站图标URL</label>
          <input v-model="siteIcon" type="text" />
        </div>
        <div class="button-group" style="justify-content: center; gap: 10px; margin-top: 20px;">
          <button @click="editModalVisible = false">取消</button>
          <button @click="saveSite">保存</button>
        </div>
      </div>
    </div>

    <!-- 模态框：添加新分类 -->
    <div v-if="addCategoryModalVisible" class="modal-overlay" @click.self="addCategoryModalVisible = false">
      <div class="modal-content">
        <h3>添加新分类</h3>
        <div class="form-group">
          <label>分类名称</label>
          <input v-model="newCategoryName" type="text" placeholder="输入分类名称" />
        </div>
        <div class="form-group">
          <label>分类图标</label>
          <div class="category-icon-picker">
            <div
                v-for="(icon, index) in categoryIcons"
                :key="index"
                class="category-icon-item"
                :class="{ selected: newCategoryIcon === icon }"
                @click="newCategoryIcon = icon"
            >
              {{ icon }}
            </div>
          </div>
        </div>
        <div class="button-group" style="justify-content: center; gap: 10px; margin-top: 20px;">
          <button @click="addCategoryModalVisible = false">取消</button>
          <button @click="saveNewCategory">保存</button>
        </div>
      </div>
    </div>

    <!-- 模态框：编辑分类图标 -->
    <div v-if="editCategoryIconModalVisible" class="modal-overlay" @click.self="editCategoryIconModalVisible = false">
      <div class="modal-content">
        <h3>编辑分类图标</h3>
        <div class="form-group">
          <label>分类名称</label>
          <input v-model="editingCategoryName" type="text" placeholder="输入分类名称" />
        </div>
        <div class="form-group">
          <label>选择新图标</label>
          <div class="category-icon-picker">
            <div
                v-for="(icon, index) in categoryIcons"
                :key="index"
                class="category-icon-item"
                :class="{ selected: editingCategoryIcon === icon }"
                @click="editingCategoryIcon = icon"
            >
              {{ icon }}
            </div>
          </div>
        </div>
        <div class="button-group" style="justify-content: center; gap: 10px; margin-top: 20px;">
          <button @click="editCategoryIconModalVisible = false">取消</button>
          <button @click="saveCategoryIconChanges">保存</button>
        </div>
      </div>
    </div>

    <!-- 时间显示区域 -->
    <div class="time-box">
      <div class="time">{{ currentTime }}</div>
      <div class="date">{{ currentDate }}</div>
    </div>

    <!-- 主容器 - 包含分类和导航图标 -->
    <div class="main-container">
      <!-- 左侧分类导航 - 优化版，添加滚动和拖拽功能 -->
      <div class="category-sidebar">
        <div class="category-list-container">
          <div class="category-list">
            <div
                v-for="(category, index) in categories"
                :key="index"
                class="category-item"
                :class="{ active: currentCategory === index, 'dragging': isCategoryDragging && categoryDragIndex === index }"
                @mousedown="startCategoryDrag(index, $event)"
                @mouseenter="handleCategoryDragHover(index)"
                @mouseleave="handleCategoryDragLeave(index)"
                @click="!isCategoryDragging && switchCategory(index)"
                @contextmenu.prevent="handleCategoryContextMenu(index, $event)"
            >
              <div class="category-icon">
                <span class="category-icon-text">{{ getCategoryIcon(index) }}</span>
              </div>
              <div class="category-text">{{ category.name }}</div>
            </div>
            <!-- 新增分类按钮 -->
            <div class="category-item add-category" @click="showAddCategoryModal">
              <div class="category-icon">
                <span class="category-icon-text">+</span>
              </div>
              <div class="category-text">添加分类</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧导航图标区域 -->
      <div class="nav-content">
        <div class="nav-head">
          <!-- 分类标题 -->
          <div class="category-title" v-if="categories[currentCategory]">
            <h2>{{ categories[currentCategory].name }}</h2>
          </div>
          <div class="search-box">
            <input
                type="text"
                @keyup.enter="handleSearch"
                placeholder="输入搜索内容"
                v-model="searchValue"
                class="search-input"
            />
            <i class="search-icon">🔍</i>
          </div>
        </div>

        <div class="nav-grid-content">
          <!-- 导航图标区域 - 基于CSS Grid布局 -->
          <div class="nav-grid" :style="{ gridTemplateColumns: gridTemplateColumns }">
            <div
                v-for="(item, index) in filteredNavList"
                :key="index"
                class="nav-item"
                :style="{
                gridColumn: `span ${getLayoutCols(item.layout)}`,
                gridRow: `span ${getLayoutRows(item.layout)}`,
                opacity: isDragging && dragIndex === index ? 0 : 1,
                transform: isDragging && dragIndex === index ? 'scale(1.1)' : 'none',
                zIndex: isDragging && dragIndex === index ? 100 : 1
              }"
                @mousedown="startDrag(index, $event)"
                @mouseenter="handleDragHover(index)"
                @mouseleave="handleDragLeave(index)"
                @click="!isDragging && openLink(item.link)"
                @contextmenu.prevent="!isDragging && handleIconContextMenu(index, $event)"
            >


              <div :class="['nav-item-inner' + item.layout, { 'hovered': item.hovered }]" :style="getLayoutCols(item.layout)==2?'align-items: start':'align-items: center'">
                <div v-if="getLayoutCols(item.layout)==2">
                  <div style="display: flex;align-items: stretch" >
                    <img :src="item.icon" alt="icon" class="nav-icon" />
                    <div class="nav-text" style="padding: 10px">{{ item.text }}</div>
                  </div>
                  <div class="nav-desc">{{item.desc}}</div>
                </div>
                <div v-else style="text-align: center">
                  <img :src="item.icon" alt="icon" class="nav-icon" />
                  <div class="nav-text">{{ item.text }}</div>
                </div>
              </div>



            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分类切换指示器 -->
    <div class="category-indicator">
      <div class="category-dot" v-for="(category, index) in categories" :key="index"
           :class="{ active: currentCategory === index }" @click="switchCategory(index)"></div>
    </div>

    <!-- 拖拽元素 -->
    <div
        v-if="isDragging"
        class="drag-item"
        :style="{
        left: dragX + 'px',
        top: dragY + 'px',
        width: dragWidth + 'px',
        height: dragHeight + 'px'
      }"
    >
      <div class="nav-item-inner">
        <img :src="filteredNavList[dragIndex].icon" alt="icon" class="nav-icon" />
        <div class="nav-text">{{ filteredNavList[dragIndex].text }}</div>
      </div>
    </div>

    <!-- 分类拖拽元素 -->
    <div
        v-if="isCategoryDragging"
        class="category-drag-item"
        :style="{
        left: categoryDragX + 'px',
        top: categoryDragY + 'px',
        width: categoryDragWidth + 'px',
        height: categoryDragHeight + 'px'
      }"
    >
      <div class="category-drag-inner">
        <span class="category-icon-text">{{ categories[categoryDragIndex].icon }}</span>
        <div class="category-text">{{ categories[categoryDragIndex].name }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue';

// 分类图标选项
const categoryIcons = ['🛠️', '💾', '👥', '📚', '🎨', '⏱️', '💻', '📱', '🎮', '🎵', '🎬', '📸', '💡', '🔧', '📝', '💰', '⚙️', '🌐', '📱', '📧', '📨', '📖', '🔍', '⚡', '🌱', '💎', '🚀', '🌟', '🌈', '🍎', '⚽', '🎯', '🔑', '📌', '📅', '📊', '📈', '📉', '💬', '👀', '🔔', '🔒', '🔓', '💻', '🖥️', '🖨️', '📱', '⌚', '💡', '🔧', '🛠️', '⚙️', '🔩', '🔨', '📦', '📁', '📂', '📄', '📑', '📓', '📔', '📒', '📕', '📗', '📘', '📙', '📚', '📖', '🔍', '🔎', '🔏', '📝', '✒️', '🖋️', '🖊️', '📌', '📍', '📎', '📏', '📐'];

// 分类数据
const categories = ref([
  { name: '开发工具', icon: '🛠️' },
  { name: '代码托管', icon: '💾' },
  { name: '技术社区', icon: '👥' },
  { name: '学习资源', icon: '📚' },
  { name: '设计资源', icon: '🎨' },
  { name: '效率工具', icon: '⏱️' }
]);

const currentCategory = ref(0);

// 按分类组织的导航数据
const categoryNavData = ref({
  '开发工具': [
    { icon: 'https://www.apifox.cn/favicon.ico', text: 'Apifox', link: 'https://www.apifox.cn/', hovered: false, layout: '1x1', category: '开发工具' },
    { icon: 'https://www.jetbrains.com/favicon.ico', text: 'JetBrains', link: 'https://www.jetbrains.com/', hovered: false, layout: '1x1', category: '开发工具' },
    { icon: 'https://code.visualstudio.com/favicon.ico', text: 'VS Code', link: 'https://code.visualstudio.com/', hovered: false, layout: '1x1', category: '开发工具' },
    { icon: 'https://www.sublimetext.com/favicon.ico', text: 'Sublime Text', link: 'https://www.sublimetext.com/', hovered: false, layout: '1x1', category: '开发工具' },
    { icon: 'https://www.gitkraken.com/favicon.ico', text: 'GitKraken', link: 'https://www.gitkraken.com/', hovered: false, layout: '1x1', category: '开发工具' }
  ],
  '代码托管': [
    { icon: 'https://github.githubassets.com/favicons/favicon.png', text: 'GitHub', link: 'https://github.com/', hovered: false, layout: '1x1', category: '代码托管' },
    { icon: 'https://gitee.com/favicon.ico', text: '码云Gitee', link: 'https://gitee.com/', hovered: false, layout: '1x1', category: '代码托管' },
    { icon: 'https://bitbucket.org/favicon.ico', text: 'Bitbucket', link: 'https://bitbucket.org/', hovered: false, layout: '1x1', category: '代码托管' },
    { icon: 'https://gitlab.com/favicon.ico', text: 'GitLab', link: 'https://gitlab.com/', hovered: false, layout: '1x1', category: '代码托管' }
  ],
  '技术社区': [
    { icon: 'https://v2ex.com/favicon.ico', text: 'V2EX', link: 'https://www.v2ex.com/', hovered: false, layout: '1x1', category: '技术社区' },
    { icon: 'https://www.zhihu.com/favicon.ico', text: '知乎', link: 'https://www.zhihu.com/', hovered: false, layout: '1x1', category: '技术社区' },
    { icon: 'https://www.csdn.net/favicon.ico', text: 'CSDN', link: 'https://www.csdn.net/', hovered: false, layout: '1x1', category: '技术社区' },
  ],
  '学习资源': [
    { icon: 'https://reactjs.org/favicon.ico', text: 'React', link: 'https://react.dev/', hovered: false, layout: '1x1', category: '学习资源' },
    { icon: 'https://leetcode.cn/favicon.ico', text: '力扣', link: 'https://leetcode.cn/', hovered: false, layout: '1x1', category: '学习资源' },
  ],
  '设计资源': [
    { icon: 'https://www.sketch.com/favicon.ico', text: 'Sketch', link: 'https://www.sketch.com/', hovered: false, layout: '1x1', category: '设计资源' },
  ],
  '效率工具': [
    { icon: 'https://www.trello.com/favicon.ico', text: 'Trello', link: 'https://www.trello.com/', hovered: false, layout: '1x1', category: '效率工具' },
    { icon: 'https://www.miro.com/favicon.ico', text: 'Miro', link: 'https://www.miro.com/', hovered: false, layout: '1x1', category: '效率工具' }
  ]
});

// 合并所有分类数据到navList
const navList = ref([]);

// 壁纸设置
const presetWallpapers = [
  { name: '默认深色', url: 'https://picsum.photos/id/1018/1920/1080' },
  { name: '科技风格', url: 'https://picsum.photos/id/180/1920/1080' },
  { name: '抽象艺术', url: 'https://picsum.photos/id/1039/1920/1080' },
  { name: '几何图案', url: 'https://picsum.photos/id/1071/1920/1080' },
  { name: '代码风格', url: 'https://picsum.photos/id/1/1920/1080' },
];

const currentBackground = ref(localStorage.getItem('background') || presetWallpapers[0].url);
const wallpaperSettingsVisible = ref(false);
const customWallpaperUrl = ref('');

// 分类拖拽相关
const isCategoryDragging = ref(false);
const categoryDragIndex = ref(-1);
const categoryDragX = ref(0);
const categoryDragY = ref(0);
const categoryDragWidth = ref(0);
const categoryDragHeight = ref(0);
const categoryDragStartX = ref(0);
const categoryDragStartY = ref(0);
const editingCategoryIndex = ref(-1);
const editingCategoryName = ref('');
const editingCategoryIcon = ref('');
const editCategoryIconModalVisible = ref(false);
const isCategoryContextMenu = ref(false);

// 保存导航数据到本地存储
const saveNavList = () => {
  // 保存分类数据
  localStorage.setItem('categories', JSON.stringify(categories.value));

  // 按分类保存数据，包括布局和顺序
  const savedData = {};
  categories.value.forEach(category => {
    savedData[category.name] = navList.value.filter(item => item.category === category.name);
  });
  localStorage.setItem('navCategoryData', JSON.stringify(savedData));
};

// 保存壁纸设置
const saveWallpaperSettings = () => {
  localStorage.setItem('background', currentBackground.value);
  wallpaperSettingsVisible.value = false;
};

// 加载本地存储数据
const loadNavData = () => {
  // 加载分类数据
  const savedCategories = JSON.parse(localStorage.getItem('categories'));
  if (savedCategories) {
    categories.value = savedCategories;
  }

  const savedData = JSON.parse(localStorage.getItem('navCategoryData'));
  if (savedData) {
    navList.value = [];
    categories.value.forEach(category => {
      const items = savedData[category.name] || [];
      navList.value = [...navList.value, ...items];
    });
  } else {
    // 如果没有保存的数据，使用默认数据
    navList.value = [];
    categories.value.forEach(category => {
      const items = categoryNavData.value[category.name] || [];
      navList.value = [...navList.value, ...items];
    });
  }
};

// 监听导航数据变化，自动保存到本地存储
watch([navList, categories], saveNavList, { deep: true });

// 右键菜单相关
const contextMenuVisible = ref(false);
const contextMenuX = ref(0);
const contextMenuY = ref(0);
const contextMenuTargetIndex = ref(-1);
const isIconContextMenu = ref(false);

// 布局设置相关
const layoutSettingsVisible = ref(false);
const selectedLayout = ref('1x1');
const targetLayoutIndex = ref(-1);

// 布局选项
const layoutOptions = [
  { value: '1x1', label: '1×1', cols: 1, rows: 1 },
  { value: '1x2', label: '1×2', cols: 1, rows: 2 },
  { value: '2x1', label: '2×1', cols: 2, rows: 1 },
  { value: '2x2', label: '2×2', cols: 2, rows: 2 },
  { value: '2x4', label: '2×4', cols: 2, rows: 4 },
];

// 模态框相关
const modalVisible = ref(false);
const newSiteName = ref('');
const newSiteUrl = ref('');
const newSiteIcon = ref('');
const newSiteDesc = ref('');

const editModalVisible = ref(false);
const siteName = ref('');
const siteUrl = ref('');
const siteIcon = ref('');
const siteDesc = ref('');


// 新增分类模态框相关
const addCategoryModalVisible = ref(false);
const newCategoryName = ref('');
const newCategoryIcon = ref('📌');

// 搜索相关
const searchValue = ref('');
const currentTime = ref('');
const currentDate = ref('');

const refreshDate = () => {
  // 获取当前时间和日期
  const date = new Date();
  currentTime.value = (
      date.getHours().toString().padStart(2, '0') + ':' +
      date.getMinutes().toString().padStart(2, '0') + ":" +
      date.getSeconds().toString().padStart(2, '0')
  );
  currentDate.value = (
      date.getMonth() + 1 + '月' +
      date.getDate() + '日 ' +
      ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()]
  );
};

// 计算当前分类的导航列表
const currentNavData = computed(() => {
  return navList.value.filter(item => item.category === categories.value[currentCategory.value].name) || [];
});

const filteredNavList = computed(() => {
  return currentNavData.value.filter(item => {
    if (!searchValue.value) return true;
    return item.text.includes(searchValue.value) || item.link.includes(searchValue.value);
  });
});

// 计算网格模板列
const gridTemplateColumns = computed(() => {
  // 查找最大的列数需求
  let maxCols = 1;
  filteredNavList.value.forEach(item => {
    const cols = getLayoutCols(item.layout);
    if (cols > maxCols) maxCols = cols;
  });

  // 设置基础列宽为80px，间隙为10px
  return `repeat(auto-fill, minmax(100px,auto))`;
});

// 从布局字符串中获取列数
const getLayoutCols = (layout) => {
  if (layout && typeof layout === 'string' && layout.includes('x')) {
    return parseInt(layout.split('x')[0]) || 1;
  }
  return 1; // 默认值
};

// 从布局字符串中获取行数
const getLayoutRows = (layout) => {
  if (layout && typeof layout === 'string' && layout.includes('x')) {
    return parseInt(layout.split('x')[1]) || 1;
  }
  return 1; // 默认值
};

// 右侧导航项拖拽相关
const isDragging = ref(false);
const dragIndex = ref(-1);
const dragX = ref(0);
const dragY = ref(0);
const dragWidth = ref(0);
const dragHeight = ref(0);
const dragStartX = ref(0);
const dragStartY = ref(0);

const startDrag = (index, event) => {
  if (event.button !== 0) return; // 只处理左键拖拽

  event.preventDefault();
  event.stopPropagation();

  isDragging.value = true;
  dragIndex.value = index;
  const element = event.currentTarget;
  const rect = element.getBoundingClientRect();

  dragWidth.value = rect.width;
  dragHeight.value = rect.height;
  dragX.value = rect.left;
  dragY.value = rect.top;
  dragStartX.value = event.clientX - rect.left;
  dragStartY.value = event.clientY - rect.top;

  // 添加拖拽事件监听
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', stopDrag);
};

const handleDrag = (event) => {
  if (!isDragging.value) return;

  dragX.value = event.clientX - dragStartX.value;
  dragY.value = event.clientY - dragStartY.value;

  // 检测是否需要交换位置
  const elements = document.querySelectorAll('.nav-item');
  const currentElement = elements[dragIndex.value];

  if (currentElement) {
    // 获取当前拖拽元素的位置和大小
    const dragRect = {
      left: dragX.value,
      top: dragY.value,
      right: dragX.value + dragWidth.value,
      bottom: dragY.value + dragHeight.value,
      width: dragWidth.value,
      height: dragHeight.value
    };

    // 查找最近的可交换位置
    let closestIndex = -1;
    let minDistance = Infinity;

    elements.forEach((element, index) => {
      if (index !== dragIndex.value) {
        const rect = element.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;

        // 计算拖拽元素中心与当前元素中心的距离
        const dragCenterX = dragRect.left + dragRect.width / 2;
        const dragCenterY = dragRect.top + dragRect.height / 2;
        const distance = Math.sqrt(
            Math.pow(dragCenterX - centerX, 2) +
            Math.pow(dragCenterY - centerY, 2)
        );

        // 如果鼠标在元素上方，并且距离更近
        if (
            event.clientX > rect.left &&
            event.clientX < rect.right &&
            event.clientY > rect.top &&
            event.clientY < rect.bottom &&
            distance < minDistance
        ) {
          minDistance = distance;
          closestIndex = index;
        }
      }
    });

    // 如果找到更近的位置，交换元素
    if (closestIndex !== -1) {
      swapItems(dragIndex.value, closestIndex);
      dragIndex.value = closestIndex;
    }
  }
};

const swapItems = (fromIndex, toIndex) => {
  if (fromIndex === toIndex) return;

  // 获取当前分类
  const categoryName = categories.value[currentCategory.value].name;

  // 获取当前分类在navList中的所有项目索引
  const categoryItemIndices = navList.value
      .map((item, i) => ({ item, index: i }))
      .filter(({ item }) => item.category === categoryName)
      .map(({ index }) => index);

  // 确保索引有效
  if (fromIndex < 0 || fromIndex >= categoryItemIndices.length ||
      toIndex < 0 || toIndex >= categoryItemIndices.length) {
    return;
  }

  // 获取实际的navList索引
  const fromNavListIndex = categoryItemIndices[fromIndex];
  const toNavListIndex = categoryItemIndices[toIndex];

  // 交换navList中的项目
  const temp = navList.value[fromNavListIndex];
  navList.value.splice(fromNavListIndex, 1);
  navList.value.splice(toNavListIndex, 0, temp);
};

const stopDrag = () => {
  isDragging.value = false;
  dragIndex.value = -1;
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDrag);

  // 确保拖拽结束后立即保存数据
  saveNavList();
};

const handleDragHover = (index) => {
  if (!isDragging.value || dragIndex.value === -1) return;

  filteredNavList.value.forEach((item, i) => {
    item.hovered = i === index && i !== dragIndex.value;
  });
};

const handleDragLeave = () => {
  filteredNavList.value.forEach(item => {
    item.hovered = false;
  });
};

// 分类菜单拖拽相关
const startCategoryDrag = (index, event) => {
  if (event.button !== 0) return; // 只处理左键拖拽

  event.preventDefault();
  event.stopPropagation();

  isCategoryDragging.value = true;
  categoryDragIndex.value = index;
  const element = event.currentTarget;
  const rect = element.getBoundingClientRect();

  categoryDragWidth.value = rect.width;
  categoryDragHeight.value = rect.height;
  categoryDragX.value = rect.left;
  categoryDragY.value = rect.top;
  categoryDragStartX.value = event.clientX - rect.left;
  categoryDragStartY.value = event.clientY - rect.top;

  // 添加拖拽事件监听
  document.addEventListener('mousemove', handleCategoryDrag);
  document.addEventListener('mouseup', stopCategoryDrag);
};

const handleCategoryDrag = (event) => {
  if (!isCategoryDragging.value) return;

  categoryDragX.value = event.clientX - categoryDragStartX.value;
  categoryDragY.value = event.clientY - categoryDragStartY.value;

  // 检测是否需要交换位置
  const elements = document.querySelectorAll('.category-item:not(.add-category)');
  const currentElement = elements[categoryDragIndex.value];

  if (currentElement) {
    // 获取当前拖拽元素的位置和大小
    const dragRect = {
      left: categoryDragX.value,
      top: categoryDragY.value,
      right: categoryDragX.value + categoryDragWidth.value,
      bottom: categoryDragY.value + categoryDragHeight.value,
      width: categoryDragWidth.value,
      height: categoryDragHeight.value
    };

    // 查找最近的可交换位置
    let closestIndex = -1;
    let minDistance = Infinity;

    elements.forEach((element, index) => {
      if (index !== categoryDragIndex.value) {
        const rect = element.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;

        // 计算拖拽元素中心与当前元素中心的距离
        const dragCenterX = dragRect.left + dragRect.width / 2;
        const dragCenterY = dragRect.top + dragRect.height / 2;
        const distance = Math.sqrt(
            Math.pow(dragCenterX - centerX, 2) +
            Math.pow(dragCenterY - centerY, 2)
        );

        // 如果鼠标在元素上方，并且距离更近
        if (
            event.clientX > rect.left &&
            event.clientX < rect.right &&
            event.clientY > rect.top &&
            event.clientY < rect.bottom &&
            distance < minDistance
        ) {
          minDistance = distance;
          closestIndex = index;
        }
      }
    });

    // 如果找到更近的位置，交换元素
    if (closestIndex !== -1) {
      swapCategoryItems(categoryDragIndex.value, closestIndex);
      categoryDragIndex.value = closestIndex;
    }
  }
};

const swapCategoryItems = (fromIndex, toIndex) => {
  if (fromIndex === toIndex) return;

  // 交换分类顺序
  const temp = categories.value[fromIndex];
  categories.value.splice(fromIndex, 1);
  categories.value.splice(toIndex, 0, temp);

  // 如果当前分类被移动，更新currentCategory
  if (currentCategory.value === fromIndex) {
    currentCategory.value = toIndex;
  } else if (currentCategory.value > fromIndex && currentCategory.value <= toIndex) {
    currentCategory.value--;
  } else if (currentCategory.value < fromIndex && currentCategory.value >= toIndex) {
    currentCategory.value++;
  }
};

const stopCategoryDrag = () => {
  isCategoryDragging.value = false;
  categoryDragIndex.value = -1;
  document.removeEventListener('mousemove', handleCategoryDrag);
  document.removeEventListener('mouseup', stopCategoryDrag);

  // 确保拖拽结束后立即保存数据
  saveNavList();
};

const handleCategoryDragHover = (index) => {
  if (!isCategoryDragging.value || categoryDragIndex.value === -1) return;

  categories.value.forEach((_, i) => {
    if (i !== categoryDragIndex.value) {
      const element = document.querySelectorAll('.category-item')[i];
      if (element) {
        element.classList.add('hovered');
      }
    }
  });
};

const handleCategoryDragLeave = () => {
  categories.value.forEach((_, i) => {
    const element = document.querySelectorAll('.category-item')[i];
    if (element) {
      element.classList.remove('hovered');
    }
  });
};

onMounted(() => {
  // 添加全局点击事件，点击其他区域关闭右键菜单
  document.addEventListener('click', closeContextMenu);
  refreshDate();

  // 加载本地存储数据
  loadNavData();

  // 定时更新时间
  const intervalId = setInterval(() => {
    refreshDate();
  }, 1000);

  // 组件卸载时清除定时器和事件监听
  onUnmounted(() => {
    clearInterval(intervalId);
    document.removeEventListener('click', closeContextMenu);
  });
});

// 右键菜单相关方法
const handleGlobalContextMenu = (event) => {
  if (isDragging.value || isCategoryDragging.value) return;

  isIconContextMenu.value = false;
  isCategoryContextMenu.value = false;
  contextMenuTargetIndex.value = -1;
  contextMenuX.value = event.clientX;
  contextMenuY.value = event.clientY;
  contextMenuVisible.value = true;
};

const handleIconContextMenu = (index, event) => {
  if (isDragging.value || isCategoryDragging.value) return;

  isIconContextMenu.value = true;
  isCategoryContextMenu.value = false;
  contextMenuTargetIndex.value = index;
  contextMenuX.value = event.clientX;
  contextMenuY.value = event.clientY;
  contextMenuVisible.value = true;
  // 阻止事件冒泡到全局上下文菜单
  event.stopPropagation();
};

const handleCategoryContextMenu = (index, event) => {
  if (isDragging.value || isCategoryDragging.value) return;

  isIconContextMenu.value = false;
  isCategoryContextMenu.value = true;
  contextMenuTargetIndex.value = index;
  contextMenuX.value = event.clientX;
  contextMenuY.value = event.clientY;
  contextMenuVisible.value = true;
  // 阻止事件冒泡到全局上下文菜单
  event.stopPropagation();
};

const closeContextMenu = () => {
  contextMenuVisible.value = false;
};

const handleIconHover = (index) => {
  if (isDragging.value) return;

  filteredNavList.value.forEach((item, i) => {
    item.hovered = i === index;
  });
};

const handleIconLeave = () => {
  filteredNavList.value.forEach(item => {
    item.hovered = false;
  });
};

const addNewSite = () => {
  closeContextMenu();
  // 重置表单
  newSiteName.value = '';
  newSiteUrl.value = '';
  newSiteIcon.value = '';
  newSiteDesc.value = '';
  modalVisible.value = true;
};

// 显示添加分类模态框
const showAddCategoryModal = () => {
  newCategoryName.value = '';
  newCategoryIcon.value = '📌'; // 默认图标
  addCategoryModalVisible.value = true;
};

// 保存新分类
const saveNewCategory = () => {
  if (!newCategoryName.value.trim()) {
    alert('请输入分类名称');
    return;
  }

  // 检查分类名是否已存在
  const exists = categories.value.some(cat => cat.name === newCategoryName.value.trim());
  if (exists) {
    alert('分类名称已存在');
    return;
  }

  // 添加新分类
  categories.value.push({
    name: newCategoryName.value.trim(),
    icon: newCategoryIcon.value
  });

  // 切换到新分类
  currentCategory.value = categories.value.length - 1;

  // 关闭模态框
  addCategoryModalVisible.value = false;
};

// 分类切换方法
const switchCategory = (index) => {
  if (index < 0 || index >= categories.value.length) return;

  currentCategory.value = index;

  // 添加分类切换动画效果
  const categoryIndicator = document.querySelector('.category-indicator');
  if (categoryIndicator) {
    categoryIndicator.classList.add('transitioning');
    setTimeout(() => {
      categoryIndicator.classList.remove('transitioning');
    }, 300);
  }
};

// 全局鼠标滚轮事件处理 - 在屏幕中间区域滚动切换分类
const handleGlobalWheel = (event) => {
  // 忽略拖拽时的滚轮事件
  if (isDragging.value || isCategoryDragging.value) return;

  // 忽略表单元素内的滚轮事件
  if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') return;

  // 判断是否在指定 class 内滚动
  if ([...event.target.classList].some(cls => cls.includes("nav-item"))) {
    return;
  }
  if ([...event.target.classList].some(cls => cls.includes("category"))) {
    return;
  }

  // 计算屏幕中间区域范围（上下各留10%的边距）
  const screenHeight = window.innerHeight;
  const middleAreaTop = screenHeight * 0.1;
  const middleAreaBottom = screenHeight * 0.9;

  // 检查鼠标位置是否在中间区域
  if (event.clientY >= middleAreaTop && event.clientY <= middleAreaBottom) {
    event.preventDefault();

    if (event.deltaY > 0) {
      // 向下滚动，切换到下一个分类
      switchCategory((currentCategory.value + 1) % categories.value.length);
    } else {
      // 向上滚动，切换到上一个分类
      switchCategory((currentCategory.value - 1 + categories.value.length) % categories.value.length);
    }
  }
};

// 壁纸设置相关方法
const showWallpaperSettings = () => {
  closeContextMenu();
  customWallpaperUrl.value = currentBackground.value;
  wallpaperSettingsVisible.value = true;
};

const selectWallpaper = (url) => {
  currentBackground.value = url;
  customWallpaperUrl.value = url;
};

const setCustomWallpaper = () => {
  if (customWallpaperUrl.value) {
    currentBackground.value = customWallpaperUrl.value;
  }
};

// 布局设置相关方法
const showLayoutSettings = () => {
  closeContextMenu();
  targetLayoutIndex.value = contextMenuTargetIndex.value;
  // 确保layout属性存在
  if (contextMenuTargetIndex.value !== -1) {
    selectedLayout.value = filteredNavList.value[contextMenuTargetIndex.value].layout || '1x1';
  }
  layoutSettingsVisible.value = true;
};


const showEditSite=()=>{
  closeContextMenu();
  // 确保layout属性存在
  if (contextMenuTargetIndex.value !== -1) {
    const item = filteredNavList.value[contextMenuTargetIndex.value]
    siteIcon.value=item.icon
    siteUrl.value=item.link
    siteName.value=item.text
    siteDesc.value=item.desc
    editModalVisible.value = true;
  }
}



const setLayout = (layout) => {
  selectedLayout.value = layout;
};

const getPreviewStyle = (option) => {
  const baseSize = 40;
  return {
    width: `${baseSize * option.cols}px`,
    height: `${baseSize * option.rows}px`,
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    border: '1px solid #409eff',
    borderRadius: '4px',
    backgroundColor: 'rgba(64, 158, 255, 0.1)',
    margin: 'auto'
  };
};

const applyLayout = () => {
  if (targetLayoutIndex.value !== -1 && contextMenuTargetIndex.value !== -1) {
    const item = filteredNavList.value[contextMenuTargetIndex.value];
    item.layout = selectedLayout.value;

    // 更新navList中的对应元素
    const categoryName = categories.value[currentCategory.value].name;
    const itemIndexInNavList = navList.value.findIndex(i =>
        i.text === item.text && i.link === item.link && i.category === categoryName
    );
    if (itemIndexInNavList !== -1) {
      navList.value[itemIndexInNavList].layout = selectedLayout.value;
    }
  }
  layoutSettingsVisible.value = false;
};

// 模态框相关方法
const saveNewSite = () => {
  if (!newSiteName.value || !newSiteUrl.value) {
    alert('请输入网站名称和URL');
    return;
  }

  // 处理图标URL
  let iconUrl = newSiteIcon.value;
  if (!iconUrl) {
    iconUrl=faviconURL(newSiteUrl.value)
  }
  // 添加新网站到当前分类
  const newSite = {
    text: newSiteName.value,
    link: newSiteUrl.value,
    desc: newSiteDesc.value,
    icon: iconUrl,
    hovered: false,
    layout: '1x1',
    category: categories.value[currentCategory.value].name // 添加到当前分类
  };

  navList.value.push(newSite);

  modalVisible.value = false;
};

// 模态框相关方法
const saveSite = () => {
  if (!siteName.value || !siteUrl.value) {
    alert('请输入网站名称和URL');
    return;
  }
  // 处理图标URL
  let iconUrl = siteIcon.value;
  if (!iconUrl) {
    iconUrl=faviconURL(siteUrl.value)
  }
   filteredNavList.value[contextMenuTargetIndex.value].desc=siteDesc.value
   filteredNavList.value[contextMenuTargetIndex.value].text=siteName.value
   filteredNavList.value[contextMenuTargetIndex.value].link=siteUrl.value
   filteredNavList.value[contextMenuTargetIndex.value].icon=iconUrl
  editModalVisible.value = false;
};
// 导航项相关方法
const openLink = (url) => {
  window.open(url, '_blank');
};

const handleSearch = () => {
  if (searchValue.value) {
    if (chrome){
      chrome.tabs.create({ active: true }, tab => {
        chrome.search.query({ text:searchValue.value, tabId: tab.id });
      });
    }else {
      window.open(`https://www.baidu.com/s?wd=${encodeURIComponent(searchValue.value)}`, '_blank');
    }
  }
};

const deleteSite = (index) => {
  closeContextMenu();
  if (confirm(`确定要删除 "${filteredNavList.value[index].text}" 吗？`)) {
    // 从navList中删除
    const item = filteredNavList.value[index];
    const itemIndexInNavList = navList.value.findIndex(i =>
        i.text === item.text && i.link === item.link && i.category === item.category
    );
    if (itemIndexInNavList !== -1) {
      navList.value.splice(itemIndexInNavList, 1);
    }
  }
};

// 获取分类图标
const getCategoryIcon = (index) => {
  if (index < categories.value.length) {
    return categories.value[index].icon;
  }
  return '📌';
};

// 重置布局
const resetLayout = () => {
  closeContextMenu();
  if (confirm(`确定要重置"${categories.value[currentCategory.value].name}"的布局吗？`)) {
    const categoryName = categories.value[currentCategory.value].name;
    const defaultItems = categoryNavData.value[categoryName] || [];

    // 重置当前分类的所有项目布局
    navList.value.forEach(item => {
      if (item.category === categoryName) {
        const defaultItem = defaultItems.find(i => i.text === item.text && i.link === item.link);
        if (defaultItem) {
          item.layout = defaultItem.layout || '1x1';
        }
      }
    });
  }
};


const importBookmarks=()=>{
  closeContextMenu();
  if (chrome){
    console.log(chrome.bookmarks)
    chrome.bookmarks.getTree(function(bookmarkTreeNodes) {
      renderBookmarkNodes(bookmarkTreeNodes)
    });
  }else {
    alert("当前环境不支持导入书签")
  }
}

function faviconURL(u) {
  if (chrome) {
    const url = new URL(chrome.runtime.getURL("/_favicon/"));
    url.searchParams.set("pageUrl", u); // this encodes the URL as well
    url.searchParams.set("size", "128");
    return url.toString();
  }else {
    return `https://www.google.com/s2/favicons?domain=${u}`
  }
}
function renderBookmarkNodes(nodes, parentPath = '') {
  nodes.forEach(node => {
    const currentPath = parentPath ? `${parentPath} > ${node.title}` : node.title;


    if (node.url) {
      // 处理书签项 - 现在可以访问完整路径
      let path=currentPath.split(">")
      let typeName="书签栏"
      if (path.length>=2){
        typeName=path[path.length-2]
      }

      console.log(node,currentPath,typeName)


      const exists = categories.value.some(cat => cat.name === typeName);
      if (!exists) {
        // 添加新分类
        categories.value.push({
          name: typeName,
          icon: "📚"
        });
      }
      let icon= faviconURL(node.url)
      // 添加新网站到当前分类
      const newSite = {
        text: node.title,
        link: node.url,
        icon: icon,
        hovered: false,
        layout: '1x1',
        category: typeName // 添加到当前分类
      };
  // 检查是否已存在相同url的站点
        const existsUrl = navList.value.some(item => item.link === newSite.link);
  // 如果不存在相同url的站点，则添加到列表中
        if (!existsUrl) {
          navList.value.push(newSite);
        }
    } else if (node.children && node.children.length > 0) {
      // 处理文件夹 - 递归时传递更新后的路径
      renderBookmarkNodes(node.children, currentPath);
    }
  });
}


// 新增删除分类方法
const deleteCategory = () => {
  closeContextMenu();

  if (isCategoryContextMenu.value) {
    editingCategoryIndex.value = contextMenuTargetIndex.value;
    if (editingCategoryIndex.value >= 0 && editingCategoryIndex.value < categories.value.length) {
      let index=editingCategoryIndex.value
      if (confirm(`确定要删除 "${categories.value[index].name}" 分类吗？该分类下的所有网站也将被删除。`)) {
        // 获取该分类下的所有网站
        const categoryName = categories.value[index].name;
        const siteToRemove = navList.value.filter(item => item.category === categoryName);

        // 从navList中删除该分类下的所有网站
        siteToRemove.forEach(site => {
          const index = navList.value.findIndex(item =>
              item.text === site.text &&
              item.link === site.link &&
              item.category === site.category
          );
          if (index !== -1) {
            navList.value.splice(index, 1);
          }
        });

        // 从分类列表中删除
        categories.value.splice(index, 1);

        // 切换到前一个分类（如果当前分类被删除）
        if (currentCategory.value >= categories.value.length) {
          currentCategory.value = categories.value.length > 0 ? categories.value.length - 1 : 0;
        }
      }

    }
  }



};

// 显示编辑分类图标模态框
const showCategoryIconSettings = () => {
  closeContextMenu();
  if (isCategoryContextMenu.value) {
    editingCategoryIndex.value = contextMenuTargetIndex.value;
    if (editingCategoryIndex.value >= 0 && editingCategoryIndex.value < categories.value.length) {
      editingCategoryName.value = categories.value[editingCategoryIndex.value].name;
      editingCategoryIcon.value = categories.value[editingCategoryIndex.value].icon;
      editCategoryIconModalVisible.value = true;
    }
  }
};

// 保存分类图标修改
const saveCategoryIconChanges = () => {
  if (editingCategoryIndex.value >= 0 && editingCategoryIndex.value < categories.value.length) {
    categories.value[editingCategoryIndex.value].icon = editingCategoryIcon.value;
    categories.value[editingCategoryIndex.value].name = editingCategoryName.value;
    saveNavList();
  }
  editCategoryIconModalVisible.value = false;
};
</script>

<style scoped>
.homepage-container {
  width: 100%;
  min-height: 100vh;
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  /* 背景遮罩层 */
  background-color: rgba(0, 0, 0, 0.4);
  background-blend-mode: overlay;
}

.time-box {
  text-align: center;
  margin-bottom: 20px;
  backdrop-filter: blur(5px);
  padding: 10px 20px;
  border-radius: 8px;
  width: 100%;
  max-width: 1200px;
}

.time {
  font-size: 60px;
  font-weight: bold;
}

.date {
  font-size: 14px;
  opacity: 0.8;
}

.main-container {
  display: flex;
  width: 100%;
  max-width: 1200px;
  gap: 10px;
}

/* 左侧分类导航 - 优化版，添加滚动和拖拽功能 */
.category-sidebar {
  width: 80px;
  position: fixed;
  left: 20px;
  top: 70px;
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 10px 0;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 100;
  transition: all 0.3s ease;
  /* 添加滚动相关样式 */
  height: calc(100vh - 140px);
  display: flex;
  align-items: center;
}

/* 分类列表容器，用于保持原有布局 */
.category-list-container {
  width: 100%;
  max-height: 100%;
  overflow-y: auto;
}
.category-list-container::-webkit-scrollbar {
  display: none;
}

.category-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0;
  margin: 0;
  list-style: none;
  width: 100%;
}

.category-item {
  width: 60px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 5px 0;
  padding: 10px 0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  position: relative;
  user-select: none;
}

.category-item:hover, .category-item.active {
  background-color: rgba(64, 158, 255, 0.2);
  transform: translateY(-3px);
  box-shadow: 0 4px 10px rgba(64, 158, 255, 0.2);
}

.category-item.active {
  background-color: rgba(64, 158, 255, 0.3);
  color: white;
}

.category-item.dragging {
  opacity: 0;
  transform: scale(1.1);
  z-index: 100;
}

.category-item.hovered:not(.dragging) {
  background-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-5px);
}

.category-icon {
  font-size: 24px;
  margin-bottom: 5px;
  position: relative;
}

.category-text {
  font-size: 12px;
  text-align: center;
}

/* 新增分类按钮样式 */
.add-category {
  background-color: rgba(255, 255, 255, 0.05);
  border: 1px dashed rgba(64, 158, 255, 0.5);
}

.add-category:hover {
  background-color: rgba(64, 158, 255, 0.1);
  transform: translateY(-3px);
}

.add-category .category-icon-text {
  font-size: 32px;
  line-height: 1;
}

/* 滚动条样式 */
.category-sidebar::-webkit-scrollbar {
  width: 6px;
}

.category-sidebar::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
}

.category-sidebar::-webkit-scrollbar-thumb {
  background: rgba(64, 158, 255, 0.5);
  border-radius: 10px;
}

.category-sidebar::-webkit-scrollbar-thumb:hover {
  background: rgba(64, 158, 255, 0.8);
}

/* 右侧导航图标区域 */
.nav-content {
  flex: 1;
  margin-left: 100px;
  display: flex;
  flex-direction: column;
}


.nav-head{
  width: 60%;
  margin: 0 auto;
}

.category-title {
  margin-bottom: 10px;
  backdrop-filter: blur(5px);
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 10px 20px;
  text-align: center;
}

.category-title h2 {
  margin: 0;
  font-size: 24px;
}

.search-box {
  position: relative;
  margin-bottom: 20px;
}

.search-input::placeholder {
  color: #fff; /* 修改为你想要的颜色 */
}

.search-input {
  width: 100%;
  height: 40px;
  padding: 0 40px 0 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 20px;
  outline: none;
  font-size: 14px;
  backdrop-filter: blur(5px);
  background-color: rgba(255, 255, 255, 0.1);
  box-sizing: border-box;
  caret-color: #fff;
  color: #fff;
}

.search-icon {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #409eff;
  cursor: pointer;
}

/* 导航网格布局 */

.nav-grid-content{
  max-height: 60vh;
  overflow-y: auto;
  overscroll-behavior: contain;
}

.nav-grid-content::-webkit-scrollbar {
  display: none;
}

.nav-grid {
  display: grid;
  grid-gap: 10px;
  width: 100%;
  transition: all 0.3s ease;
}

.nav-item {
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.05);
  overflow: hidden;
  backdrop-filter: blur(5px);
}

.nav-item:hover:not(.dragging) {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(1.02);
  z-index: 20;
}

.nav-item.hovered:not(.dragging) {
  background-color: rgba(255, 255, 255, 0.15);
  transform: scale(1.04);
  z-index: 30;
}

.nav-item-inner1x1 {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-radius: 8px;
  margin: 0 auto;
  width: 100px;
  height: 100px;
  box-sizing: border-box;
}

.nav-item-inner1x2 {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-radius: 8px;
  margin: 0 auto;
  width: 100px;
  height: 200px;
  box-sizing: border-box;
}

.nav-item-inner2x1 {
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-radius: 8px;
  width: 200px;
  height: 100px;
  box-sizing: border-box;
}

.nav-item-inner2x2 {
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-radius: 8px;
  width: 200px;
  height: 200px;
  box-sizing: border-box;
}

.nav-item-inner2x4 {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border-radius: 8px;
  width: 200px;
  height: 400px;
  box-sizing: border-box;
}

.nav-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 8px;
  border-radius: 50%;
  object-fit: cover;
}

.nav-text {
  font-size: 12px;
  max-width: 80px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}

.nav-desc{
  font-size: 12px;
  display: -webkit-box;              /* 弹性伸缩盒子 */
  -webkit-line-clamp: 2;             /* 限制最多显示3行 */
  -webkit-box-orient: vertical;      /* 垂直排列子元素 */
  overflow: hidden;                  /* 超出隐藏 */
  text-overflow: ellipsis;           /* 超出部分显示省略号 */
}


/* 拖拽元素样式 */
.drag-item {
  position: fixed;
  pointer-events: none;
  z-index: 1000;
  border-radius: 8px;
  background-color: rgba(30, 30, 30, 0.95);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
  transition: all 0.1s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
}

/* 分类拖拽元素样式 */
.category-drag-item {
  position: fixed;
  pointer-events: none;
  z-index: 1000;
  border-radius: 12px;
  background-color: rgba(30, 30, 30, 0.95);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.4);
  transition: all 0.1s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  backdrop-filter: blur(10px);
}

.category-drag-inner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  background-color: rgba(45, 45, 45, 0.95);
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  min-width: 150px;
  padding: 5px;
  backdrop-filter: blur(10px);
  >div{
    border-radius: 10px;
  }
}

.menu-item {
  padding: 8px 15px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
}

.menu-item:hover {
  background-color: #434547;
}

.menu-item.danger {
  color: #ff4d4f;
}

.menu-item.danger:hover {
  background-color: #ff4d4f;
  color: white;
}

/* 布局设置面板样式 */
.layout-settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.layout-settings-panel {
  background-color: rgba(45, 45, 45, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  padding: 20px;
  width: 100%;
  max-width: 400px;
  backdrop-filter: blur(10px);
}

.layout-settings-panel h3 {
  margin-top: 0;
  margin-bottom: 20px;
  text-align: center;
}

.layout-options {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.layout-option {
  cursor: pointer;
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  transition: all 0.2s;
}

.layout-option:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

.layout-option.active {
  background-color: rgba(64, 158, 255, 0.1);
  border: 1px solid #409eff;
}

.layout-preview {
  margin-bottom: 8px;
}

.layout-icon {
  width: 20px;
  height: 20px;
  background-color: #409eff;
  border-radius: 4px;
}

.layout-label {
  font-size: 12px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.button-group button {
  padding: 8px 15px;
  margin-left: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.button-group button:first-child {
  background-color: #444;
  color: #fff;
}

.button-group button:last-child {
  background-color: #409eff;
  color: #fff;
}

.button-group button:first-child:hover {
  background-color: #555;
}

.button-group button:last-child:hover {
  background-color: #308ce7;
}

/* 壁纸设置面板样式 */
.wallpaper-settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.wallpaper-settings-panel {
  background-color: rgba(45, 45, 45, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  padding: 20px;
  width: 100%;
  max-width: 600px;
  backdrop-filter: blur(10px);
}

.wallpaper-settings-panel h3 {
  margin-top: 0;
  margin-bottom: 20px;
  text-align: center;
}

.wallpaper-options {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
  margin-bottom: 20px;
}

.wallpaper-option {
  cursor: pointer;
  text-align: center;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.2s;
}

.wallpaper-option:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

.wallpaper-option.active {
  background-color: rgba(64, 158, 255, 0.1);
  border: 1px solid #409eff;
}

.wallpaper-preview {
  width: 100%;
  height: 80px;
  background-size: cover;
  background-position: center;
  border-radius: 4px;
  margin-bottom: 5px;
}

.wallpaper-label {
  font-size: 12px;
}

.custom-wallpaper {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.custom-wallpaper h4 {
  margin-top: 0;
  margin-bottom: 10px;
}

.custom-wallpaper .form-group {
  display: flex;
}

.custom-wallpaper-input {
  flex: 1;
  height: 36px;
  padding: 0 10px;
  border: none;
  border-radius: 4px 0 0 4px;
  outline: none;
  font-size: 14px;
  background-color: rgba(255, 255, 255, 0.8);
}

.custom-wallpaper-btn {
  height: 36px;
  padding: 0 15px;
  border: none;
  border-radius: 0 4px 4px 0;
  background-color: #409eff;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.custom-wallpaper-btn:hover {
  background-color: #308ce7;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(5px);
}

.modal-content {
  background-color: rgba(45, 45, 45, 0.95);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  padding: 20px;
  width: 100%;
  max-width: 400px;
  backdrop-filter: blur(10px);
}

.modal-content h3 {
  margin-top: 0;
  margin-bottom: 20px;
  text-align: center;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #444;
  background-color: rgba(255, 255, 255, 0.8);
  color: #000;
  border-radius: 4px;
  box-sizing: border-box;
}

/* 分类图标选择器 */
.category-icon-picker {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  margin-top: 10px;
}

.category-icon-item {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.2s;
}

.category-icon-item:hover {
  background-color: rgba(64, 158, 255, 0.1);
}

.category-icon-item.selected {
  background-color: rgba(64, 158, 255, 0.2);
  border: 1px solid #409eff;
}

/* 分类指示器 */
.category-indicator {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
  padding: 10px 15px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  background-color: rgba(255, 255, 255, 0.1);
  z-index: 50;
  transition: all 0.3s ease;
}

.category-indicator.transitioning {
  opacity: 0.7;
}

.category-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
}

.category-dot.active {
  width: 24px;
  border-radius: 4px;
  background-color: #409eff;
}
</style>